import uuid

import requests

from common.logger_factory import Log
from config import configuration
from config.dynamic_configuration import ConfigCenter

rpc_ex_url = f"http://{configuration.REMOTE_MSG_HOST}:{configuration.REMOTE_MSG_PORT}/rpc"


class RemoteDefinition:
    CODE_KEY = "code"
    MESSAGE_KEY = "msg"
    DATA_KEY = "data"
    SUCCESS_CODE = 200
    SERVER_NOT_FOUND_CODE = 404

    @staticmethod
    def failure(msg):
        return {
            RemoteDefinition.CODE_KEY: RemoteDefinition.SERVER_NOT_FOUND_CODE,
            RemoteDefinition.MESSAGE_KEY: msg
        }

    @staticmethod
    def set_post(params):
        try:
            response = requests.post(rpc_ex_url, json=params).json()
        except requests.ConnectionError:
            Log.error(f"消息发送失败，原因是：无法连接到{rpc_ex_url}")
            return RemoteDefinition.failure("无法连接到远程消息服务")
        return response


class RemoteSmsService:

    @staticmethod
    def sent_heartbeat_msg(msg):
        message = f"[心跳通知]{msg}"
        payload = {
            "jsonrpc": "2.0",
            "method": "sent_custom_text_msg",
            "params": {
                "msg": message,
                "context": {
                    "app_key": ConfigCenter.get_ding_app_key(),
                    "app_secret": ConfigCenter.get_ding_app_secret(),
                    "open_conversation_id": ConfigCenter.get_ding_open_conversation_id(),
                    "robot_code": ConfigCenter.get_ding_robot_code()
                }
            },
            "id": str(uuid.uuid4())
        }
        return RemoteDefinition.set_post(payload)
